// File Name: key_ctrl.h
// Author: kukukukuku~
// Date: 2024-06-25

#ifndef __KEY_CTRL_H
#define __KEY_CTRL_H

#include "at32f421.h"

#define KEY_GPIO_CRM                CRM_GPIOB_PERIPH_CLOCK
#define KEY_UP_GPIO_PORT            GPIOB
#define KEY_UP_GPIO_PIN             GPIO_PINS_7
#define KEY_LEFT_GPIO_PORT          GPIOB
#define KEY_LEFT_GPIO_PIN           GPIO_PINS_6
#define KEY_DOWN_GPIO_PORT          GPIOB
#define KEY_DOWN_GPIO_PIN           GPIO_PINS_5
#define KEY_RIGHT_GPIO_PORT         GPIOB
#define KEY_RIGHT_GPIO_PIN          GPIO_PINS_4
#define KEY_MID_GPIO_PORT           GPIOB
#define KEY_MID_GPIO_PIN            GPIO_PINS_3

#define KEY_TMR_CRM                 CRM_TMR17_PERIPH_CLOCK
#define KEY_TMR                     TMR17
#define KEY_TMR_DIV                 (1200)
#define KEY_TMR_PR                  (10000)
#define KEY_TMR_IRQ                 TMR17_GLOBAL_IRQn
#define KEY_TMR_HANDLE              TMR17_GLOBAL_IRQHandler

#define KEY_NUM                     (5)
#define KEY_UP_INDEX                (0)
#define KEY_LEFT_INDEX              (1)
#define KEY_DOWN_INDEX              (2)
#define KEY_RIGHT_INDEX             (3)
#define KEY_MID_INDEX               (4)

#define KEY_UP_LONG_JUDGE_NUM       (15)    //*100ms
#define KEY_LEFT_LONG_JUDGE_NUM     (15)    //*100ms
#define KEY_DOWN_LONG_JUDGE_NUM     (15)    //*100ms
#define KEY_RIGHT_LONG_JUDGE_NUM    (15)    //*100ms
#define KEY_MID_LONG_JUDGE_NUM      (15)    //*100ms

#define KEY_CLICK_BEEP              (50)
#define KEY_LONG_BEEP               (200)

#define KEY_CLICK_BEEP_MIN          (20)
#define KEY_CLICK_BEEP_MAX          (200)
#define KEY_LONG_BEEP_MIN           (200)
#define KEY_LONG_BEEP_MAX           (2000)

//按键状态
typedef enum KeyState
{
    KEY_STATE_RELEASE,      //松开
    KEY_STATE_CLICK,        //单击
    KEY_STATE_CLICK_LONG,   //长按
}KeyState;

//按键处理
typedef enum KeyHandle
{
    KEY_HANDLE_NONE,    //不处理
    KEY_HANDLE_CLICK,   //单击处理
    KEY_HANDLE_LONG,    //长按处理
}KeyHandle;

//按键对象
typedef struct Key
{
    gpio_type *gpioPort;
    uint32_t gpioPin;
    uint16_t pressCount;            //按下次数
    uint16_t longPressJudgeNum;     //长按判断时间 *100ms
    uint16_t longPressJudgeCnt;     //长按时间计数值 *100ms
    KeyState state;                 //按键状态
    KeyHandle handle;               //按键处理
    uint8_t longPressScanFlag : 1;  //长按扫描标志
    uint8_t pressPolarity : 1;      //按下时的电平
    uint8_t pressFlag : 1;          //按下标志
}Key, *pKey;

extern Key key[KEY_NUM];    //按键对象

extern uint8_t keyAllReleaseFlag;  //所有按键全部松开标志
extern uint8_t keyLockFlag;        //按键锁定标志

extern uint16_t keyClickBeep;  //按键短按蜂鸣时间
extern uint16_t keyLongBeep;   //按键长按蜂鸣时间

//Key配置
void key_config(void);

#endif //__KEY_CTRL_H
